import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import '../styles/login.css';
import Particles from '../utils/Particles';
import { LockClosedIcon, UserIcon, AtSymbolIcon, FingerPrintIcon } from '@heroicons/react/solid';

function App() {
  const navigate = useNavigate();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [error, setError] = useState('');
  const [captcha, setCaptcha] = useState(null);
  const [captchaImage, setCaptchaImage] = useState('');
  const [captchaUUID, setCaptchaUUID] = useState('');

  // 设置请求拦截器
  const setupInterceptor = () => {
    const originalFetch = window.fetch;
    window.fetch = async (url, options = {}) => {
      const token = localStorage.getItem('access_token');
      if (token) {
        options.headers = {
          ...options.headers,
          'Authorization': `Bearer ${token}`,
        };
      }
      return originalFetch(url, options);
    };
  };

  const handleSubmit = async (e) => {
    // 登录逻辑
    try {
      console.log('开始登录中...');
      //setupInterceptor();
      e.preventDefault();
      if (!username || !password || !captcha) {
        setError('请输入账号、密码和验证码');
        return;
      }

      console.log('请求参数: username:', username, ',captcha:', captcha, ',uuid:', captchaUUID, ',rememberMe:', rememberMe);

      const response = await fetch('http://localhost:8088/auth/user/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
          captcha,
          uuid: captchaUUID,
          rememberMe,
        }),
      });

      console.log('登录请求返回值: ', response);

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '登录失败');
      }

      const data = await response.json();
      console.log('登录成功:', data);

      // 存储 token 到 localStorage
      localStorage.setItem('access_token', data.data.access_token);
      localStorage.setItem('expires_in', data.data.expires_in);
      // 处理登录成功逻辑（例如跳转页面）
      navigate('/admin');
    } catch (err) {
      setError(err.message || '登录请求失败');
    }
  };

  useEffect(() => {
    const fetchCaptcha = async () => {
      try {
        const response = await fetch('http://localhost:8088/code');
        const data = await response.json();
        if (data.code === 200) {
          // 直接使用接口返回的 Base64 字符串
          setCaptchaImage(`data:image/png;base64,${data.img}`);
          setCaptchaUUID(data.uuid);
        } else {
          setError('验证码获取失败');
        }
      } catch (err) {
        setError('验证码请求失败');
      }
    };
    fetchCaptcha();
  }, []);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 to-blue-700 overflow-hidden">
      <Particles />

      <div className="container mx-auto px-4 py-16 relative z-10">
        <div className="flex flex-col lg:flex-row items-center justify-center gap-12">
          {/* 左侧品牌区 */}
          <div className="w-full lg:w-1/2 text-center lg:text-left">
            <div className="bg-white bg-opacity-10 backdrop-blur-lg rounded-2xl p-8 shadow-xl">

              <div className="w-32 h-32 mx-auto lg:mx-0 bg-blue-500 rounded-full flex items-center justify-center mb-6">
                {/* 3D图标占位 */}
                <svg className="w-20 h-20 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                  <path fillRule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clipRule="evenodd" />
                </svg>
              </div>
              <h1 className="text-4xl font-bold text-white mb-4">科技云平台</h1>
              <p className="text-blue-100 text-xl">连接未来 · 智享科技</p>
            </div>
          </div>

          {/* 右侧登录表单 */}
          <div className="w-full lg:w-1/2 max-w-md">
            <form
              onSubmit={handleSubmit}
              className="bg-white bg-opacity-10 backdrop-blur-lg rounded-2xl p-8 shadow-xl border border-white border-opacity-20"
            >
              {error && (
                <div className="bg-red-500 text-white px-4 py-2 rounded mb-4 animate-slide-down">
                  {error}
                </div>
              )}

              <h2 className="text-2xl font-bold text-white mb-6 text-center">用户登录</h2>

              {/* 邮箱输入 */}
              <div className="mb-4">
                <label className="block text-blue-100 text-sm font-medium mb-2" htmlFor="email">
                  账号
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <AtSymbolIcon className="h-5 w-5 text-blue-300" />
                  </div>
                  <input
                    id="username"
                    type="text"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    className="w-full pl-10 pr-3 py-3 bg-white bg-opacity-10 border border-white border-opacity-20 rounded-lg text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                    placeholder="账号"
                  />
                </div>
              </div>

              {/* 密码输入 */}
              <div className="mb-6">
                <label className="block text-blue-100 text-sm font-medium mb-2" htmlFor="password">
                  密码
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <LockClosedIcon className="h-5 w-5 text-blue-300" />
                  </div>
                  <input
                    id="password"
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full pl-10 pr-3 py-3 bg-white bg-opacity-10 border border-white border-opacity-20 rounded-lg text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                    placeholder="密码"
                  />
                </div>
              </div>
              {/* 验证码输入 */}
              <div className="mb-6">
                <label className="block text-blue-100 text-sm font-medium mb-2" htmlFor="captcha">
                  验证码
                </label>
                <div className="flex items-center">
                  <input
                    id="captcha"
                    type="text"
                    value={captcha}
                    onChange={(e) => setCaptcha(e.target.value)}
                    className="w-full px-3 py-3 bg-white bg-opacity-10 border border-white border-opacity-20 rounded-lg text-white placeholder-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
                    placeholder="验证码"
                  />
                  <img
                    src={captchaImage}
                    alt="验证码"
                    className="ml-2 h-10 w-24 cursor-pointer"
                    onClick={() => window.location.reload()}
                  />
                </div>
              </div>

              {/* 记住我 & 忘记密码 */}
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center">
                  <input
                    id="remember-me"
                    type="checkbox"
                    checked={rememberMe}
                    onChange={(e) => setRememberMe(e.target.checked)}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="remember-me" className="ml-2 block text-sm text-blue-100">
                    记住我
                  </label>
                </div>
                <div className="text-sm">
                  <a href="#" className="font-medium text-blue-300 hover:text-blue-200">
                    忘记密码?
                  </a>
                </div>
              </div>

              {/* 登录按钮 */}
              <button
                type="submit"
                className="w-full bg-gradient-to-r from-blue-500 to-teal-400 hover:from-teal-400 hover:to-blue-500 text-white font-medium py-3 px-4 rounded-lg shadow-md hover:shadow-lg transition duration-300 ease-in-out"
              >
                登录
              </button>

              {/* 社交登录 */}
              <div className="mt-6">
                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-white border-opacity-20"></div>
                  </div>
                  {/* <div className="relative flex justify-center text-sm mb-4">
                    <span className="px-2 bg-transparent text-blue-100">或通过以下方式登录</span>
                  </div> */}
                </div>
                {/* <div className="grid grid-cols-2 gap-4 mt-2">
                  <button
                    type="button"
                    className="w-full flex items-center justify-center py-2 px-4 border border-white border-opacity-20 rounded-lg shadow-sm text-sm font-medium text-white bg-white bg-opacity-5 hover:bg-opacity-10 transition"
                  >
                    <GoogleIcon className="h-5 w-5 mr-2" />
                    Google
                  </button>
                  <button
                    type="button"
                    className="w-full flex items-center justify-center py-2 px-4 border border-white border-opacity-20 rounded-lg shadow-sm text-sm font-medium text-white bg-white bg-opacity-5 hover:bg-opacity-10 transition"
                  >
                    <GithubIcon className="h-5 w-5 mr-2" />
                    GitHub
                  </button>
                </div> */}
              </div>

              {/* 注册链接 */}
              <div className="mt-6 text-center">
                <p className="text-sm text-blue-100">
                  新用户?{' '}
                  <a href="#" className="font-medium text-blue-300 hover:text-blue-200">
                    立即注册
                  </a>
                </p>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;